import Vue from "vue"
import Vuex from "vuex"
import persiste from "vuex-persistedstate"
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    shopCart: [],
  },
  mutations: {
    addCart(state, data) {
      let index = state.shopCart.findIndex((item) => item.id === data.id)
      if (index === -1) {
        state.shopCart.push(data)
      } else {
        state.shopCart[index].count += data.count
      }
    },
    setAllCkd(state, val) {
      state.shopCart.forEach((item, index) => {
        Vue.set(item, "ckd", val)
      })
    },
    setOneCkd(state, obj) {
      let index = state.shopCart.findIndex((el) => (el.id = obj.id))
      state.shopCart[index].ckd = obj.ckd
    },
    setCount(state, obj) {
      let index = state.shopCart.findIndex((el) => (el.id = obj.id))
      state.shopCart[index].count = obj.count
    },
  },
  getters: {
    calcPrice(state) {
      let sum = 0
      state.shopCart.forEach((item) => {
        if (item.ckd) {
          sum += item.pri * item.count
        }
      })
      return sum
    },
  },
  actions: {},
  modules: {},
  plugins: [persiste()],
})
